import {SorterResult} from 'antd/es/table/interface.d';
import {FormatPaginationProps, TablePaginationConfig, OptionItem} from './utils.d';

export const pager2antd = (pager: FormatPaginationProps) => {
    const newPager = {} as TablePaginationConfig;
    Object.keys(pager || {}).forEach(key => {
        if (key !== 'pageNum' && key !== 'count') {
            // @ts-ignore
            newPager[key] = pager[key];
        }
    });
    return {
        current: pager?.pageNum,
        total: pager?.count,
        ...newPager,
    };
};

export const pager2serve = (pager: TablePaginationConfig) => ({
    pageNum: pager?.current,
    ...(pager || {})
});

export const formatOptions = (options: OptionItem[]) => options?.map(item => ({
    value: item.key,
    label: item.label
})) || [];

// 数字千分位处理，默认保留两位小数
export const thousandthNum = (number:number, precision = 2) => {
    if (isNaN(number)) {
        return number || '--';
    }
    return (+number).toLocaleString('zh', {
        maximumFractionDigits: precision || 2
    });
};

// 金额类数据处理，添加￥单位并千分位处理并默认保留两位小数
export const thousandthMoney = (number: number, precision = 2) => {
    if (isNaN(number)) {
        return number || '--';
    }
    return (+number).toLocaleString('zh', {
        maximumFractionDigits: precision || 2,
        style: 'currency',
        currency: 'CNY',
    });
};

// 率类数据处理，添加￥单位并千分位处理并默认保留两位小数
export const ratio2percent = (number: number, precision = 2) => {
    if (isNaN(number)) {
        return number || '--';
    }
    return (+number).toLocaleString('zh', {
        maximumFractionDigits: precision || 2,
        style: 'percent',
    });
};

// 单位为分的金额转换成元
export const fen2yuan = (money: number) => {
    if (isNaN(money)) {
        return money || '--';
    }
    return thousandthMoney(money / 100);
};

// 排序转化
export const convertSort = (antSortInfo: SorterResult<{}>, ascend = 1, descend = 2) => {
    const sortTypeMap = {
        ascend,
        descend,
    };
    const {order, field} = antSortInfo || {};
    return {
        sortType: order ? sortTypeMap[order] : undefined,
        sortField: order ? field : undefined
    };
};

// 排序转化(protable)
export const convertProSort = (proSortInfo:{}, ascend = 1, descend = 2) => {
    const sortTypeMap = {
        ascend,
        descend,
    };
    console.log('proSortInfo', proSortInfo);
    const sortParams = {} as {sortField?: string; sortType?:string};
    if (proSortInfo) {
        Object.keys(proSortInfo).forEach(key => {
            sortParams.sortField = key;
            sortParams.sortType = sortTypeMap[proSortInfo[key]];
        });
    }
    return sortParams;
};

